package com.spzx.product.service.impl;


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.domain.Category;
import com.spzx.product.mapper.CategoryMapper;
import com.spzx.product.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Override
    public List<Category> listByPid(Long pid) {
        //查询pid的下一级分类集合
        List<Category> categories = this.list(Wrappers.lambdaQuery(Category.class)
                .eq(Category::getParentId, pid)
                .orderByDesc(Category::getOrderNum));
        //遍历查询每个分类是否有下一级
        if(!CollectionUtils.isEmpty(categories)){
            categories.forEach(category -> {
                long count = this.count(Wrappers.lambdaQuery(Category.class)
                        .eq(Category::getParentId, category.getId()));
                category.setHasChildren(count>0);
            });
        }

        return categories;
    }

    @Override
    public List<Long> selectCategoryIdsByC3Id(Long category3Id) {
        String cIds = baseMapper.selectCategoryIdsByC3Id(category3Id);
        List<Long> idList = Arrays.stream(cIds.split(",")).toList().stream().map(s -> Long.parseLong(s)).collect(Collectors.toList());
        return idList;
    }
}

